<template>
    <div>
        <div class="search-box">
            <el-form ref="dataFormRef" :inline="true" :model="form" :rules="rules" class="demo-form-inline">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="数据源表名称" prop="sourceName">
                            <el-input v-model="form.sourceName" clearable placeholder="请输入数据源表名称" />
                        </el-form-item>
                        <el-form-item label="数据源表code" prop="sourceCode">
                            <el-input v-model="form.sourceCode" :disabled="true" clearable placeholder="请输入数据源表code"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" style="text-align: center">
                        <el-button type="primary" @click="resetForm()">保存</el-button>
                        <el-button @click="closeForm">关闭</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <page-main>
            <div class="btn-box">
                <el-button type="primary" @click="showAddFrom">新增字段</el-button>
                <el-button :disabled="selectItem.length==0" @click="deleteRow">删除</el-button>
                <el-button :disabled="selectItem.length==0" @click="editItem('off')">停用</el-button>
                <el-button :disabled="selectItem.length==0" @click="editItem('on')">启用</el-button>
            </div>
            <PubilcTable :table-data="tableData" :list-config="columns" :showSelect="true" :showPageSize="false" :page-data="pageData" @on-action="onAction" @on-selectChange="changeSelectItem" @on-switchChange="switchChange"/>
        </page-main>
        <eForm :dialog-visible="dialogVisible" :is-add="isAdd" :formData="formData" @on-submit="formSubmit" @handle-close="handleClose"/>
    </div>
</template>
<script  setup>
import config from '@/settings'
import { reactive, ref } from 'vue'
import eForm from '../components/addDataForm.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/api/index'

let router = useRouter();
const route = useRoute();
const form = ref({})
const dataFormRef = ref(null)
const dialogVisible = ref(false)
const isAdd = ref('add')
const pageData = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const formData = ref({})
const options = ref({})
const selectItem = ref([])

const validatesourceCode = (rule, value, callback) => {
    let reg = /^[a-zA-Z]\w+$/
    let status = true
    const arr = config.validateLisOptions
    arr.forEach((item)=>{
        if(value === item){
            callback(new Error('不能为关键字'+item))
            status = false
        }
    })
    if (status) {
        if(!reg.test(value)){
            callback(new Error('26个英文字母和0-9的自然数+下划线组成，首字符为字母'))
        }else{
            callback()
        }
    }
}

const rules = reactive({
    sourceName: [
        {
            required: true,
            message: '请输入数据源表名称',
            trigger: 'blur'
        }
    ],
    sourceCode: [
        {
            required: true,
            message: '请输入数据源表code',
            trigger: 'blur'
        },
        { validator: validatesourceCode, trigger: 'blur' }
    ]
})

const tableData = ref([])
const editIndex = ref(null)
const OPERTATE = [
    { alias: 'edit', label: '编辑' },
]

const columns = [
    { alias: 'fieldName', label: '字段名称' },
    { alias: 'fieldCode', label: '字段code' },
    { alias: 'fieldType', label: '字段类型' },
    { alias: 'fieldLength', label: '字段长度' },
    { alias: 'only', label: '是否唯一' },
    { alias: 'primary', label: '是否为主键', type:'switch'},
    { alias: 'status', label: '状态', type:'switch' },
    { label: '操作', listArr: OPERTATE, width: '280px', fixed: 'right', type: 'action' }
]


onMounted(()=>{
    const data = localStorage.getItem('addDataParams');
    if(data){
        console.log(data, 'data')
        form.value = {...JSON.parse(data)}
        form.value.sourceName = form.value.docName
        form.value.sourceCode = form.value.docCode
        if(form.value.metaData && form.value.metaData !== ' ' && form.value.metaData !== 'null'){
            console.log(form.value.metaData ,' form.value.metaData')
            tableData.value = [...JSON.parse(form.value.metaData)]
            tableData.value.forEach((item)=>{
                if(item.status === 1){
                    item.status = true
                }else{
                    item.status = false
                }
            })
        }else{
            tableData.value = []
        }
        pageData.total = tableData.value.length
    }
})

const deleteRow = ()=>{
    if(selectItem.value.length > 0){
        ElMessageBox.confirm('确定删除此枚举信息吗？删除后将不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const newList = tableData.value.filter((item)=>{
                let tar = true
                selectItem.value.forEach((item2)=>{
                  if (item.fieldCode === item2.fieldCode) {
                      tar = false
                  }
                })
                if (tar) {
                    return item
                }
            });
            tableData.value = newList
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
        })
    }else{
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const editItem =(type)=>{
    if(selectItem.value.length > 0){
        let text = ''
        if(type === 'off'){
            text = '停用'
        }else{
            text = '启用'
        }
        ElMessageBox.confirm('确定'+ text  +'选中的字段吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            tableData.value.forEach((item)=>{
                selectItem.value.forEach((item2)=>{
                    if(item.fieldCode === item2.fieldCode){
                        if(type === 'off'){
                            item.status = false
                        }else{
                            item.status = true
                        }
                    }
                })
            });
            ElMessage({
                type: 'success',
                message: text + '成功!'
            });
        })
    }else{
        ElMessage({
            type: 'error',
            message: '请至少勾选一项数据!'
        });
    }
}
const editRow = (row,index) => {
    formData.value = row
    editIndex.value = index
    dialogVisible.value = true
    isAdd.value = 'edit'
}
const onAction = ([item, row, index]) => {
    const obj = {
        'edit': editRow
    }
    if (typeof item === 'string') {
        pageData[item] = row
        if (item === 'pageSize') pageData.pageNum = 1
        obj[item]()
    } else {
        obj[item.alias](row,index)
    }
}
const changeSelectItem = (data)=>{
    selectItem.value = data
}
const showAddFrom = () => {
    formData.value = {}
    dialogVisible.value = true
    isAdd.value = 'add'
}
const formSubmit = (data, type)=>{
    if(type === 'add'){
        let contiue = true
        try{
            tableData.value.forEach((item)=>{
                if(data.fieldCode === item.fieldCode){
                    ElMessage({
                        type: 'error',
                        message: '字段code与该表已有字段code不能相同!'
                    });
                    contiue = false
                    throw Error()
                }
                if(data.fieldName === item.fieldName){
                    ElMessage({
                        type: 'error',
                        message: '字段名称不能相同!'
                    });
                    contiue = false
                    throw Error()
                }
            });
        }catch(err){
            console.log(err)
        }
        if(contiue){
            tableData.value = [...tableData.value, data]
        }
    }else{
        let contiue = true
        try{
            tableData.value.forEach((item,index)=>{
                if(index !== editIndex.value){
                    if(data.fieldCode === item.fieldCode){
                        ElMessage({
                            type: 'error',
                            message: '字段code与该表已有字段code不能相同!'
                        });
                        contiue = false
                        throw Error()
                    }
                    if(data.fieldName === item.fieldName){
                        ElMessage({
                            type: 'error',
                            message: '字段名称不能相同!'
                        });
                        contiue = false
                        throw Error()
                    }
                }
            });
        }catch(err){
            console.log(err)
        }
        if(contiue){
            tableData.value = (tableData.value || []).map((item,index) => {
                if(index === editIndex.value){
                    return item = data
                }else{
                    return item
                }
            })
        }
    }
}
const handleClose = val => {
    dialogVisible.value = val
}
const closeForm = ()=>{
    localStorage.removeItem('addDataParams');
    router.push({
        name: 'dataTable'
    })
}
const resetForm = ()=>{
    if (!dataFormRef) return
    dataFormRef.value.validate(valid => {
        if(valid){
            (tableData.value || []).forEach((item)=>{
                if(item.status === true){
                    item.status = 1
                }else{
                    item.status = 0
                }
            })
            form.value.tableFields = tableData.value
            form.value.metaData = null
            if(form.value){
                const params = {...form.value}
                api.dataMaintenance.updateTable(params).then((res)=>{
                    ElMessage({
                        type: 'success',
                        message: '保存成功!'
                    });
                    closeForm()
                }).catch(()=>{
                    tableData.value.forEach((item)=>{
                        if(item.status === 1){
                            item.status = true
                        }else{
                            item.status = false
                        }
                    })
                })
            }
        }
    })
}

const switchChange = (data)=>{
    const [val, row, alias] = [...data]
    if(alias === 'primary'){
        tableData.value.forEach((item)=>{
            item[alias] = false
            if(row.fieldCode === item.fieldCode){
                item[alias] = val
            }
        })
    }
}
</script>

<style lang="scss" scoped>
.search-box {
  margin-top: 20px;
  padding: 0 20px;
}
.btn-box {
  margin-bottom: 20px;
}
</style>
